//
//  SY_Par_AttendanceViewController.m
//  ChatDemo-UI2.0
//
//  Created by zz on 17/2/17.
//  Copyright © 2017年 zz. All rights reserved.
//

#import "SY_Par_AttendanceViewController.h"
#import "FDCalendar.h"
#import "SYPickerView.h"
#import "DropDownMenu2.h"
#import "SY_Par_CurAttendanceViewController.h"
#import "SY_Activity_Model.h"
#import "SYMessageTool.h"
@implementation ParAtdselBtn

+ (instancetype)buttonWithFrame:(CGRect)frame title:(NSString *)title target:(SEL)selector target:(id)target{
    
    ParAtdselBtn *btn = [ParAtdselBtn buttonWithType:UIButtonTypeCustom];
    [btn setFrame:frame];
    
    [btn addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];
    [btn setBackgroundColor:[UIColor colorWithHexString:@"#e6f6fc"]];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor colorWithHexString:@"#1ebfff"] forState:UIControlStateNormal];
    btn.layer.borderWidth = 0.5;
    btn.titleLabel.font = [UIFont systemFontOfSize:13];
    btn.layer.cornerRadius = 4;
    btn.layer.borderColor = [UIColor colorWithHexString:@"#1ebfff"].CGColor;
    return btn;
}

@end

@implementation ParAttendLabel

+ (instancetype)labelWithFrame:(CGRect)frame desText:(NSString *)desText conText:(NSString *)conText{
    
    ParAttendLabel *label = [[ParAttendLabel alloc] init];
    label.desText = desText;
    label.contentText = conText;
    label.frame = frame;
    label.textColor = [UIColor colorWithHexString:@"#3b3b3b"];
    label.font = [UIFont systemFontOfSize:15];
    label.text = [NSString stringWithFormat:@"%@:   %@",desText,conText];
    return label;
}

- (void)setContentText:(NSString *)contentText{
    
    _contentText = contentText;
    
    self.text = [NSString stringWithFormat:@"%@:   %@",self.desText,self.contentText];
}


@end


@interface SY_Par_AttendanceViewController ()<FDCalendarDelegate,UIPickerViewDelegate,UIPickerViewDataSource,DropDownMenu2Delegate>


@property (nonatomic,strong) UIScrollView *bgScrollView; //大背景scroll


@property (nonatomic,strong) UIView *headerView; //头部选择控件


@property (nonatomic,strong) ParAtdselBtn *selClassBtn; //选择班级按钮

@property (nonatomic,strong) ParAtdselBtn *selDateBtn; //选择时间按钮

@property (nonatomic,strong) FDCalendar *calendar; //日历

@property (nonatomic,strong) UIView *recodView;  //当日考勤记录

@property (nonatomic,strong) UIView *bottomView; //底部view

@property (nonatomic,strong) ParAttendLabel *qingjiaLabel; //请假类型


@property (nonatomic,strong) ParAttendLabel *amArrLabel; //上午到校的记录
@property (nonatomic,strong) ParAttendLabel *pmArrLabel; //下午到校的记录

@property (nonatomic,strong) ParAttendLabel *amLeaLabel; //上午离校的记录
@property (nonatomic,strong) ParAttendLabel *pmLeaLabel; //下午离校的记录

@property (nonatomic,strong) UIView *paddingBottomView; //距下48px的空白view

@property (nonatomic,strong) SYPickerView *stuPicker; //选择学生
@property (nonatomic,strong) UIPickerView *datePicker; //选择月份


@property (nonatomic,copy) NSString *qingjiaTypeStr; //后台返回的请假类型

@end

@implementation SY_Par_AttendanceViewController{
    
    NSMutableArray * stuAndClassArray;
    
    NSString * stuId;
    NSString * className;
    NSString * stuName;
    NSString *classId;

    NSDate *selDate;
    NSString *selDateStr;
    
    
    //记录Picker当前选择的日期
    NSInteger currentPickerIndex;
    NSInteger currentPickerDetailIndex;
    
    
}

#pragma mark -Getter
- (UIScrollView *)bgScrollView{
    
    if (_bgScrollView == nil) {
        
        _bgScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, VIEW_WIDTH, VIEW_HEIGHT - SafeAreaTopHeight)];
        [_bgScrollView setBackgroundColor:colorFromHex(@"#F5F8FA")];
        _bgScrollView.showsVerticalScrollIndicator = NO;
        _bgScrollView.showsHorizontalScrollIndicator = NO;

        [_bgScrollView addSubview:self.headerView];
        
        [_bgScrollView addSubview:self.calendar];
    
        [_bgScrollView addSubview:self.recodView];
        
        [_bgScrollView addSubview:self.bottomView];
        
        [_bgScrollView addSubview:self.paddingBottomView];
        
        _bgScrollView.contentSize = CGSizeMake(SCREENWIDTH, CGRectGetMaxY(self.bottomView.frame) + 30);
    }
    
    return _bgScrollView;
}

- (UIView *)headerView{
    
    if (_headerView == nil) {
        
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 88)];
        _headerView.backgroundColor = [UIColor whiteColor];
        //选择学生label
        UILabel *labelStu = [[UILabel alloc] initWithFrame:CGRectMake(22, 17, 65, 16)];
        labelStu.font = [UIFont systemFontOfSize:15];
        labelStu.textColor = [UIColor colorWithHexString:@"#3b3b3b"];
        labelStu.text = @"选择宝宝";
        [_headerView addSubview:labelStu];
        
        //选择学生按钮
        _selClassBtn = [ParAtdselBtn buttonWithFrame:CGRectMake(CGRectGetMaxX(labelStu.frame) + 8, 12, 192, 26) title:@"李小二  一年级四班" target:@selector(selStudent) target:self];
        [_headerView addSubview:_selClassBtn];
        
        //选择时间label
        UILabel *labelCls = [[UILabel alloc] initWithFrame:CGRectMake(22, CGRectGetMaxY(_selClassBtn.frame) + 12 + 5, 65, 16)];
        labelCls.text = @"选择时间";
        labelCls.font = [UIFont systemFontOfSize:15];
        labelCls.textColor = [UIColor colorWithHexString:@"#3b3b3b"];
        [_headerView addSubview:labelCls];
        
        //选择时间按钮
        _selDateBtn = [ParAtdselBtn buttonWithFrame:CGRectMake(CGRectGetMaxX(labelCls.frame) + 8, CGRectGetMaxY(_selClassBtn.frame) + 12, 92, 26) title:@"2017年2月" target:@selector(selDate) target:self];
        [_headerView addSubview:_selDateBtn];

    }
    
    return _headerView;
}

- (FDCalendar *)calendar{
    
    if (!_calendar) {
        
        _calendar = [[FDCalendar alloc]initWithCurrentDate:[NSDate date]];
        _calendar.delegete = self;
        _calendar.today = [NSDate date];
        
        _calendar.frame = CGRectMake(0, CGRectGetMaxY(self.headerView.frame) + 10, SCREENWIDTH, 338);
    }
    
    return _calendar;
}

- (UIView *)recodView{
    
    if (!_recodView) {
        
        _recodView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.calendar.frame), SCREENWIDTH, 44)];
        _recodView.backgroundColor = [UIColor whiteColor];
        
        UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(15, 0, SCREENWIDTH - 15, 0.5)];
        line1.backgroundColor = [UIColor colorWithHexString:@"#dedede"];
        [_recodView addSubview:line1];
        
        UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake(15, 43.5, SCREENWIDTH - 15, 0.5)];
        line2.backgroundColor = [UIColor colorWithHexString:@"#dedede"];
        [_recodView addSubview:line2];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 14, 300, 16)];
        label.textColor = [UIColor colorWithHexString:@"#3b3b3b"];
        label.font = [UIFont systemFontOfSize:15];
        label.text = @"当日考勤记录";
//        label.centerY = _recodView.centerY;
        [_recodView addSubview:label];
    }
    
    return _recodView;
}

- (UIView *)bottomView{
    
    if (!_bottomView) {
        
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.recodView.frame), SCREENWIDTH, 180)];
        _bottomView.backgroundColor = [UIColor whiteColor];
        
        UILabel *qingjiaTypeLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 12, 100, 16)];
        qingjiaTypeLabel.text = @"请假";
        qingjiaTypeLabel.font = [UIFont systemFontOfSize:15];
        qingjiaTypeLabel.textColor = [UIColor colorWithHexString:@"#979797"];
        [_bottomView addSubview:qingjiaTypeLabel];
        
        _qingjiaLabel = [ParAttendLabel labelWithFrame:CGRectMake(15, CGRectGetMaxY(qingjiaTypeLabel.frame) + 12, 200, 16) desText:@"类型" conText:@"病假"];
        [_bottomView addSubview:_qingjiaLabel];
        
        if (_qingjiaTypeStr.length <= 0) { //没有请假
            
            _qingjiaLabel.y = 0;
            _qingjiaLabel.height = 0;
            
            qingjiaTypeLabel.y = 0;
            qingjiaTypeLabel.height = 0;
        }
        
        UILabel *amLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(_qingjiaLabel.frame) + 12, 100, 16)];
        amLabel.text = @"上午";
        amLabel.font = [UIFont systemFontOfSize:15];
        amLabel.textColor = [UIColor colorWithHexString:@"#979797"];
        [_bottomView addSubview:amLabel];
        
        _amArrLabel = [ParAttendLabel labelWithFrame:CGRectMake(15, CGRectGetMaxY(amLabel.frame) + 12, (SCREENWIDTH - 30) / 2 , 16) desText:@"到校" conText:@"暂无考勤记录"];
        [_bottomView addSubview:_amArrLabel];
        
        _amLeaLabel = [ParAttendLabel labelWithFrame:CGRectMake(15 + (SCREENWIDTH - 30) / 2, CGRectGetMaxY(amLabel.frame) + 12, (SCREENWIDTH - 30) / 2, 16) desText:@"离校" conText:@"暂无考勤记录"];
        [_bottomView addSubview:_amLeaLabel];

        
        UILabel *pmLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(_amArrLabel.frame) + 12, 100, 16)];
        pmLabel.text = @"下午";
        pmLabel.font = [UIFont systemFontOfSize:15];
        pmLabel.textColor = [UIColor colorWithHexString:@"#979797"];
        [_bottomView addSubview:pmLabel];

        
        _pmArrLabel = [ParAttendLabel labelWithFrame:CGRectMake(15, CGRectGetMaxY(pmLabel.frame) + 12, (SCREENWIDTH - 30) / 2, 16) desText:@"到校" conText:@"暂无考勤记录"];
        [_bottomView addSubview:_pmArrLabel];
        
        _pmLeaLabel = [ParAttendLabel labelWithFrame:CGRectMake(15 + (SCREENWIDTH - 30) / 2, CGRectGetMaxY(pmLabel.frame) + 12, (SCREENWIDTH - 30) / 2, 16) desText:@"离校" conText:@"暂无考勤记录"];
        [_bottomView addSubview:_pmLeaLabel];
    }
    
    return _bottomView;
}

- (UIView *)paddingBottomView{
    
    if (!_paddingBottomView) {
        
        _paddingBottomView.backgroundColor = [UIColor redColor];
        _paddingBottomView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.bottomView.frame), SCREENWIDTH, 24)];
        _paddingBottomView.backgroundColor = [UIColor whiteColor];
    }
    
    return _paddingBottomView;
}

- (SYPickerView *)stuPicker{

    if (!_stuPicker) {
        
        _stuPicker = [[SYPickerView alloc] initWithFrame:CGRectZero];
        
    }
    
    return _stuPicker;
}

#pragma mark -LifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navBar.nav_titleLabel.text = @"考勤";
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self.view addSubview:self.bgScrollView];
    
    [self DownStuAndClassList]; //获取学生与班级
    
   self.navBar.rightImg.hidden = NO;
   self.navBar.rightButton.hidden = NO;
   
   self.navBar.rightImg.image = [UIImage imageNamed:@"ios_more_"];
    [self.navBar.rightButton addTarget:self action:@selector(rightTapAction:) forControlEvents:UIControlEventTouchUpInside];
//
//    UIBarButtonItem *rightBarBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithOriginalName:@"ios_more_"] style:UIBarButtonItemStyleDone target:self action:@selector(rightTapAction)];
//    self.navigationItem.rightBarButtonItem = rightBarBtn;
    
//    [self.view addSubview:self.stuPicker];
}

- (void)changeReadState{
   
   SY_Activity_Model * model = [[SY_Activity_Model alloc]init];
   model.readState = 1;
   model.infoid = _infoID;
   model.msgid = _magID;
   [SYMessageTool updataMessageModel2:model];
   
}

#pragma mark -UIPickerViewDataSource && UIPickerViewDelegate


#pragma mark -Actions

//选择学生
- (void)selStudent{

    
    SYPickerView *picker = [[SYPickerView alloc] initWithFrame:CGRectZero];
    picker.pickerMode = SYPickerModeStudent;
    picker.indexOfType = currentPickerIndex;
    picker.indexOfDetailType = currentPickerDetailIndex;
    picker.sourceArray = stuAndClassArray;
    picker.sureBlock = ^(NSDictionary *dict,NSInteger indexOfType,NSInteger indexOfDetailType){
      
        //取消当前选择的日
//        [self.calendar setValue:nil forKeyPath:@"centerCalendarItem.selectedIndexPath"];
        
        //给picker赋选中值
        self ->currentPickerDetailIndex = indexOfDetailType;
        self ->currentPickerIndex = indexOfType;
        
        self->stuName = [dict objectForKey:@"studentname"];
        self->stuId = [dict objectForKey:@"studentid"];
        
        NSArray *arr=[dict objectForKey:@"item"];
        if (arr.count>0) {
            self->className=[[arr objectAtIndex:indexOfDetailType] objectForKey:@"classname"];
            self->classId=[[arr objectAtIndex:indexOfDetailType] objectForKey:@"classid"];
        }
        
        //赋值
        [self->_selClassBtn setTitle:[NSString stringWithFormat:@"%@ %@",self->stuName,self->className] forState:UIControlStateNormal];
        
        //请求当天考勤记录
        
        if (!self->selDate) {
            self->selDate = [NSDate date];
        }
        [self didSelectedDate:self->selDate];
        
        [self getMonthRecod:self ->selDateStr];
        
    };
    [picker show];
}

//选择时间
- (void)selDate{
    
    SYPickerView *picker = [[SYPickerView alloc] initWithFrame:CGRectZero];
    picker.pickerMode = SYPickerModeMonth;
    
    
    picker.sureBlock = ^(NSDictionary *dict,NSInteger indexOfType,NSInteger indexOfDetailType){
        
        NSString *monthSel = [dict objectForKey:@"month"];
        NSString *yearSel = [dict objectForKey:@"year"];
        
        NSCharacterSet* nonDigits =[[NSCharacterSet decimalDigitCharacterSet] invertedSet];
        
        int monthInt =[[monthSel stringByTrimmingCharactersInSet:nonDigits] intValue];
        
        
        NSString *monthStr = (monthInt + 1) < 10 ? [NSString stringWithFormat:@"0%d",monthInt]:[NSString stringWithFormat:@"%d",monthInt];
        
        NSString *yearStr = [NSString stringWithFormat:@"%ld",(long)[yearSel integerValue]];
        
        NSString *dateStr = [NSString stringWithFormat:@"%@%@",yearSel,monthSel];
        
        [self ->_selDateBtn setTitle:dateStr forState:UIControlStateNormal];
        
        
        
        NSString *dateSelStr = [NSString stringWithFormat:@"%@-%02d",yearStr,[monthStr intValue]];
        NSDateFormatter *formatter1 =[[NSDateFormatter alloc]init];
        [formatter1 setDateFormat:@"yyyy-MM"];
        [formatter1 setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];
        
        if (![dateSelStr isEqualToString:self ->selDateStr]) {  //选择的不是当前月份
            
            [formatter1 setDateFormat:@"yyyy-MM-01"];  //默认传1号数据
            
            NSDate *date = [formatter1 dateFromString:dateSelStr];
            
            [self didSelectedDate:date];
        }
        
        self ->selDateStr = dateSelStr;  //记录当前选择月份
        
        self.calendar.date = [formatter1 dateFromString:dateSelStr];
        [self getMonthRecod:dateSelStr];
        
        self->selDate = [formatter1 dateFromString:dateSelStr];
    };
    [picker show];
}

//更多
- (void)rightTapAction:(UIButton *)sender{
    
//    DropTable *table = [[DropTable alloc] init];
//    table.lists = @[@"考勤统计"];
//    table.delegate = self;
    UIWindow *window=KeyWindow;
    DropDownMenu2 *table = [DropDownMenu2 shareDropDownMenu];
    NSArray * arr = @[@"考勤统计"];
    table.delegate = self;
    table.backViewFlag = 1;
    table.flag = YES;
    [table setDropDownMenuParameterWithcellContents:arr andWidth:130];
    [table hideDropDown:sender];
    [window addSubview:table];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -DropTableDelegate
- (void) niDropDownDelegateMethod:(DropDownMenu2 *) sender{

        
        SY_Par_CurAttendanceViewController *vc = [[SY_Par_CurAttendanceViewController alloc] init];
        vc.studentsArr = stuAndClassArray;
        [self.navigationController pushViewController:vc animated:YES];
        
    
}

#pragma mark -FDCalendarDelegate
- (void)didSelectedDate:(NSDate *)date{
    
    selDate = date;
    
    //选择日期,调接口
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    
    [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];
    NSString *dateStr = [formatter stringFromDate:date];
    
    BaseModel *param = [BaseModel param];
    
    param.method = @"api_rollcallstudentdate_info";
    param.datetime = dateStr;
    param.classid = classId;
    param.studentid = stuId;
    
    __weak typeof(self) weakSelf = self;
    
    [Utils get:nil parameters:param.mj_keyValues success:^(NSInteger recode, id jsonObject) {
        
        NSDictionary *dict = [jsonObject objectForKey:@"re_data"];
        
        NSString *afternoonarrayStr = [dict objectForKey:@"afternoonarray"];
        NSString *afternoonleave = [dict objectForKey:@"afternoonleave"];
        NSString *beforenoonarray = [dict objectForKey:@"beforenoonarray"];
        NSString *beforenoonleave = [dict objectForKey:@"beforenoonleave"];
        
        self ->_qingjiaTypeStr = [dict objectForKey:@"leaveinfo"];
        
        //从新布局bottomview
        [self ->_bottomView removeFromSuperview];
        self ->_bottomView = nil;
        [self bottomView];
        [weakSelf.bgScrollView addSubview:self ->_bottomView];
        [weakSelf.bgScrollView setContentSize:CGSizeMake(SCREENWIDTH, CGRectGetMaxY(weakSelf.bottomView.frame) + 30)];

        [self->_amArrLabel setContentText:beforenoonarray];
        [self->_amLeaLabel setContentText:beforenoonleave];
        [self->_pmArrLabel setContentText:afternoonarrayStr];
        [self->_pmLeaLabel setContentText:afternoonleave];
        
        
        
    } failure:^(NSInteger recode, NSError *error) {
        
        
    }];
}

#pragma mark -Request
- (void)DownStuAndClassList
{
    
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
//    [dict setObject:@"api_leave_getstudentandclass" forKey:@"method"];
    [dict setObject:USERID forKey:@"parentid"];
   
    [Utils Java_get:@"api/getChildClass" parameters:dict success:^(NSInteger recode, id jsonObject) {
        
        NSArray *array = [jsonObject objectForKey:@"re_data"];
        self->stuAndClassArray = [NSMutableArray arrayWithArray:array];
        
        //获取第一个孩子 与对应的第一个班级
        NSDictionary *dict = [array objectAtIndex:0];
        self->stuName = [dict objectForKey:@"studentname"];
        self->stuId = [dict objectForKey:@"studentid"];
        
        NSDictionary *classDict = [[dict objectForKey:@"item"] firstObject];
        self -> className = [classDict objectForKey:@"classname"];
        self -> classId = [classDict objectForKey:@"classid"];
        
        [self -> _selClassBtn setTitle:[NSString stringWithFormat:@"%@  %@",self ->stuName,self->className] forState:UIControlStateNormal];
        
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy年MM月"];
        
        NSString *time = [formatter stringFromDate:date];
        
        [self -> _selDateBtn setTitle:time forState:UIControlStateNormal];
        //获取当天考勤记录
        [self didSelectedDate:[NSDate date]];
        
        //获取当月考勤记录
//        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM"];
        self->selDateStr = [formatter stringFromDate:date];
        [self getMonthRecod:[formatter stringFromDate:[NSDate date]]];
        
    } failure:^(NSInteger recode, NSError * error){
        
    }];
    
}

//家长得到某班某学生考勤记录
- (void)getMonthRecod:(NSString *)date{
    
    BaseModel *model = [BaseModel param];
    model.method = @"sy_rollcall_student";
    model.classid = classId;
    model.studentid = stuId;
    model.date = date;
    
    [Utils get:nil parameters:model.mj_keyValues success:^(NSInteger recode, id jsonObject) {
        
        [self ->_calendar setMarkArr:[jsonObject objectForKey:@"re_data"]];
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];
        [formatter setDateFormat:@"yyyy-MM"];
        self->_calendar.date = [formatter dateFromString:date];
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}


@end
